<template>
  <VTable ref="tableRef" v-bind="tableOptions">
    <template #form="{ form }">
      <el-cascader v-model="form.auth_site" placeholder="授权站点" :options="options.auth_site" :props="{multiple: true, emitPath: false}" collapse-tags-tooltip
        :show-all-levels="false" collapse-tags filterable clearable style="min-width: 160px" />
      <VSelect v-model="form.shop_ids" placeholder="店铺名称" :options="options.shop" multiple collapse-tags showCheckAll style="min-width: 240px" confusedPaste paste />
      <VCascader v-model="form.department_ids" placeholder="组织部门" type="1" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-model="form.shop_statuses" placeholder="状态" :options="options.shop_status" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-model="form.amazon_site_opens" placeholder="是否开通" :options="options.amazon_site_open" multiple collapse-tags style="min-width: 160px" />
      <VCascader v-model="form.preferred_saleman_id" placeholder="首选业务员" multiple collapse-tags style="min-width: 160px" />
      <VCascader v-model="form.salesman_id" placeholder="业务员" multiple collapse-tags style="min-width: 160px" />
      <VCascader v-model="form.preferred_customer_service_id" placeholder="首选客服人员" multiple collapse-tags style="min-width: 160px" />
      <VCascader v-model="form.customer_service_id" placeholder="客服人员" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-model="form.auth_statuses" placeholder="授权状态" :options="options.auth_status" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-model="form.ad_auth_statuses" placeholder="广告是否授权" :options="options.ad_auth_status" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-model="form.is_download_orders" placeholder="是否下载订单/报表" :options="options.open" multiple collapse-tags style="min-width: 180px" />
      <VSelect v-model="form.is_pre_generate" placeholder="是否预生成追踪号" :options="options.open" multiple collapse-tags style="min-width: 170px" />
      <VSelect v-model="form.is_platform_shipment" placeholder="是否标记平台发货" :options="options.open" multiple collapse-tags style="min-width: 170px" />
      <VSelect v-model="form.company_ids" placeholder="公司" :options="options.company" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-model="form.shop_types" placeholder="店铺类型" :options="options.shop_type" multiple collapse-tags style="min-width: 160px" />
      <VGroup>
        <el-select v-model="form.dateRange.type" style="width: 130px">
          <el-option label="授权日期" value="auth_date"></el-option>
        </el-select>
        <el-date-picker v-model="form.dateRange.value" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          style="max-width: 260px" />
      </VGroup>
      <VGroup>
        <el-select v-model="form.input.type" style="width: 100px">
          <el-option label="SellerID" value="seller_id"></el-option>
        </el-select>
        <el-input v-model="form.input.value" placeholder="请输入" class="w-60" />
      </VGroup>
    </template>
    <template #toolbar_btns>
      <VButton auth="/base/shop/amazon/create" type="primary" icon="DocumentAdd" @click="create(tableRef)">添加店铺</VButton>
      <el-button @click="handleBatch('aditSalesman')">修改业务员</el-button>
      <el-button @click="handleBatch('brand')">默认品牌</el-button>
      <EditOrder :tableRef="tableRef" :options="options" @success="query" />
      <VExport auth="/base/shop/amazon/export" mainKey="shop_id" name="shop_amazon" :tableRef="tableRef" task class="ml-auto" />
    </template>
  </VTable>
  <Add ref="addRef" :options="options" @success="query" />
  <BatchAuth ref="batchAuthRef" :options="options" @success="query" />
  <UpdateAuth ref="updateAuthRef" :options="options" @success="query" />
  <AdAuth ref="adAuthRef" :options="options" @success="query" />
  <AditSalesman ref="aditSalesmanRef" :options="options" @success="query" />
  <Brand ref="brandRef" :options="options" @success="query" />
  <VLog ref="logRef" />
  <Register ref="registerRef" />
  <Credit ref="creditRef" />
  <Collect ref="collectRef" />
  <Balance ref="balanceRef" />
  <Performance ref="performanceRef" />
  <Feedback ref="feedbackRef" />
</template>
  
<script setup lang="jsx">
import api from './api'
import shopApi from '@/views/shop/api'
import Add from './Add'
import AdAuth from './AdAuth'
import BatchAuth from './BatchAuth'
import UpdateAuth from './UpdateAuth'
import Performance from './Performance'
import Feedback from './Feedback'
import AditSalesman from '../../AditSalesman'
import Brand from '../../Brand'
import Register from '../../Register'
import Credit from '../../Credit'
import Collect from '../../Collect'
import EditOrder from '../../EditOrder'
import Balance from './Balance'
import { getOption } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
import { spanMethod } from '@/utils'

const baseName = 'shop_amazon'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const aditSalesmanRef = ref()
const brandRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const shop_ids = selection.map(d => d.shop_id)
  // const showLoading = () => loadings[name] = true
  // const closeLoading = () => loadings[name] = false
  const handle = {
    aditSalesman: () => {
      aditSalesmanRef?.value.open(shop_ids)
    },
    brand: () => {
      brandRef?.value.open(shop_ids)
    }
  }
  handle[name]()
}
// 单行操作
const batchAuthRef = ref()
const updateAuthRef = ref()
const adAuthRef = ref()
const registerRef = ref()
const creditRef = ref()
const collectRef = ref()
const performanceRef = ref()
const feedbackRef = ref()
const balanceRef = ref()
const handleRow = (name, row, rowIndex) => {
  // console.log('name', name)
  const { shop_id, status } = row
  const showLoading = (name = 'handle') => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = (name = 'handle') => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    BatchAuth: () => {
      batchAuthRef?.value.open(row)
    },
    updateAuth: () => {
      updateAuthRef?.value.open(row.update_auth)
    },
    edit: () => {
      addRef?.value.open(shop_id)
    },
    look: () => {
      addRef?.value.open(shop_id, true)
    },
    delete: () => {
      ElMessageBox.confirm('是否确认删除？', '取消', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          showLoading()
          shopApi.delete({ shop_ids: [shop_id] }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          }).finally(() => {
            closeLoading()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    status: () => {
      showLoading()
      const { status_info } = row
      shopApi.status({ shop_ids: [shop_id], status: status_info.status === '启用' ? 2 : 1 }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(() => {
        closeLoading()
      })
    },
    log: () => {
      logRef?.value.open({ type: baseName, record_id: shop_id })
    },
    adAuth: () => {
      adAuthRef?.value.open(shop_id)
    },
    register: () => {
      registerRef?.value.open(shop_id)
    },
    credit: () => {
      creditRef?.value.open(shop_id)
    },
    collect: () => {
      collectRef?.value.open(shop_id)
    },
    performance: () => {
      performanceRef?.value.open(shop_id)
    },
    feedback: () => {
      feedbackRef?.value.open(shop_id)
    },
    balance: () => {
      balanceRef?.value.open(shop_id)
    },
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  id: 'shop-amazon',
  border: true,
  rowConfig: { height: 160 },
  scrollY: { enabled: true, oSize: 10 },
  spanMethod: ags => spanMethod({...ags, fields: ['amazon_account_name']}),
  formConfig: {
    data: {
      amazon_site_opens: [2],
      dateRange: { type: 'auth_date', value: '' }, // 组合
      input: { type: 'seller_id', value: '' }, // 组合
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 50 },
    {
      title: '账号名称', field: 'amazon_account_name', minWidth: 120, slots: {
        default: ({ row }) => <div>
          <VText value={row.amazon_account_name} line={2} />
          <VText title='SellerID' value={row.auth_info.seller_id} line={1} />
          <VText value='新增授权' type='button' onClick={() => handleRow('BatchAuth', row)} />
        </div>
      }
    },
    {
      title: '店铺账号', minWidth: 220, slots: {
        default: ({ row }) => <div>
          <VText title='店铺名称' value={row.shop_info.shop_name} />
          <VText title='区域' value={row.shop_info.area} />
          <VText title='授权站点' value={row.shop_info.site} />
        </div>
      }
    },
    // {
    //   title: '基本信息', minWidth: 220, slots: {
    //     default: ({ row }) => <div>
    //       <VText title='平台账号' value={row.basic_info.platform_account} />
    //       <VText title='店铺名' value={row.basic_info.amazon_shop_name} />
    //       <VText title='品牌' value={row.basic_info.brand} />
    //       <VText value={row.basic_info.shop_type} />
    //     </div>
    //   }
    // },
    {
      title: '分配信息', minWidth: 220, slots: {
        default: ({ row }) => <div>
          <VText title='一级部门' value={row.alloc_info.first_level_department} />
          <VText title='二级部门' value={row.alloc_info.second_level_department} />
          <VText title='首选业务员' value={row.alloc_info.preferred_saleman_name} />
          <VText title='首要客服' value={row.alloc_info.preferred_customer_service_name} />
          <VText title='业务员' value={row.alloc_info.saleman_name} line='2' />
        </div>
      }
    },
    {
      title: '状态', minWidth: 160, slots: {
        default: ({ row }) => <div>
          <VText title='店铺状态'>
            <div>
              <VStatus status={row.status_info.status === '启用'} />
            </div>
          </VText>
          <VText title='前台状态' value={row.status_info.font_status} />
          <VText title='SP-API接口状态' value={row.status_info.sp_api_status} />
          <VText title='广告接口状态' value={row.status_info.ad_api_status} />
          <VText title='是否开通' value={row.status_info.amazon_site_open} />
        </div>
      }
    },
    {
      title: '授权状态', minWidth: 170, slots: {
        default: ({ row }) => <div>
          <VText title='SP-API授权'>
            <div>
              <VStatus status={row.auth_status.sp_api_auth === '正常'} auth />
            </div>
          </VText>
          <VText title='广告授权'>
            <div>
              <VStatus status={row.auth_status.ad_api_auth === '正常'} auth onAuth={() => handleRow('adAuth', row)} />
            </div>
          </VText>
        </div>
      }
    },
    // {
    //   title: '前台访问地址ID', minWidth: 140, slots: {
    //     default: ({ row }) => <VText value={row.font_url} type='link' onClick={() => window.open(row.font_url, '_blank')} line='3' />
    //   }
    // },
    {
      title: '店铺绩效', minWidth: 220, slots: {
        default: ({ row }) => <div>
          <VText title='账户状况评级 (AHR)' value={row.performance_info.account_health_rating} />
          <VText title='迟发率' value={row.performance_info.late_shipment_rate} />
          <VText title='配送前取消率' value={row.performance_info.pre_fulfillment_cancellation_rate} />
          <VText title='有效追踪率' value={row.performance_info.valid_tracking_rate} />
          <VButton auth="/base/shop/amazon/performance" link type="primary" onClick={() => handleRow('performance', row)}>查看全部<el-icon class='ml-1'><DArrowRight /></el-icon></VButton>
        </div>
      }
    },
    {
      title: 'FeedBack', minWidth: 150, slots: {
        default: ({ row }) => <div>
          <VText title='一星' value={row.feedback_info.star1} />
          <VText title='二星' value={row.feedback_info.star2} />
          <VText title='三星' value={row.feedback_info.star3} />
          <VText title='四星' value={row.feedback_info.star4} />
          <VText title='五星' value={row.feedback_info.star5} />
          <VText title='Count' value={row.feedback_info.count} />
          <VButton auth="/base/shop/amazon/feedback-count" link type="primary" onClick={() => handleRow('feedback', row)}>查看全部<el-icon class='ml-1'><DArrowRight /></el-icon></VButton>
        </div>
      }
    },
    // {
    //   title: '赛盒授权信息', minWidth: 180, slots: {
    //     default: ({ row }) => <div>
    //       <VStatus status={row.saihe_info.saihe_channel_id} auth />
    //       <VText title='赛盒渠道ID' value={row.saihe_info.saihe_channel_id} />
    //       <VText title='赛盒渠道名称' value={row.saihe_info.saihe_channel_name} line='2' title-position='top' />
    //     </div>
    //   }
    // },
    {
      title: '资产信息', field: 'assets_info', minWidth: 220, slots: {
        default: ({ row }) => <div>
          <VText title='紫鸟账号' value={row.assets_info.ziniao_account} />
          <VText title='IP' value={row.assets_info.ziniao_ip} />
          <VText title='存续周期' value={row.assets_info.period} />
          <VText title='续费时间' value={row.assets_info.renewal_time} />
        </div>
      }
    },
    {
      title: '财务信息', minWidth: 150, slots: {
        default: ({ row }) => <div>
          <VText title='余额' value={row.financial_info.balance} />
          <VText title='最近结算' value={row.financial_info.latest_settle_date} />
          <el-button link type="primary" onClick={() => handleRow('balance', row)}>余额明细</el-button>
        </div>
      }
    },
    {
      title: '操作', width: 120, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { status_info: { status } } = row
          return <div class='nm flex flex-wrap gap-1'>
            <VButton auth="/base/shop/amazon/edit" link type="primary" onClick={() => handleRow('edit', row)} class='m-0'>编辑</VButton>
            <VButton auth="/base/shop/amazon/delete" link type="danger" onClick={() => handleRow('delete', row, rowIndex)} class='m-0'>删除</VButton>
            <VButton auth="/base/shop/amazon/delete" link type="primary" onClick={() => handleRow('updateAuth', row, rowIndex)} class='m-0'>更新授权</VButton>
            {row.auth_status.ad_api_auth === '异常' && <VButton auth="/base/shop/amazon/ad-auth" link type="primary" onClick={() => handleRow('adAuth', row)} class='m-0'>广告授权</VButton>}
            <VButton auth="/base/shop/amazon/status" link type="primary" onClick={() => handleRow('status', row)} class='m-0'>{status === '启用' ? '禁用' : '启用'}</VButton>
            {/* <el-button link type="primary" onClick={() => handleRow('log', row)} class='m-0'>设置拉单</el-button> */}
            <VButton auth="/base/shop/amazon/log" link type="primary" onClick={() => handleRow('log', row)} class='m-0'>查看日志</VButton>
          </div>
        }
      }
    }
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => {
        const { platform_name, shop_id } = JSON.parse(sessionStorage.getItem('_setForm') || '{}')
        if (platform_name === 'amazon') {
          form = { shop_ids: [shop_id] }
          tableRef?.value.setForm(form)
          sessionStorage.setItem('_setForm', '{}')
        }
        return api.query({ ...form, ...page })
      }
    }
  }
})
onActivated(() => {
  const { platform_name, shop_id } = JSON.parse(sessionStorage.getItem('_setForm') || '{}')
  if (platform_name === 'amazon') {
    tableRef?.value.setForm({ shop_ids: [shop_id] })
    query()
    sessionStorage.setItem('_setForm', '{}')
  }
})
</script>
  